﻿using Endos.Wodo.Domain;
using NHibernate;
using NHibernate.Linq;
using System;

namespace Endos.Wodo.Persistence
{
    internal class DataContext : IDataContext
    {
        private readonly ISession session;

        public DataContext(IDataInitializer dataInitializer)
        {
            session = (dataInitializer as DataInitializer).Session;
        }

        public IQuery<T> CreateQuery<T>(Action<IFetch<T>> action = null)
            where T : Entity
        {
            return new Query<T>(session.Query<T>(), action);
        }

        public void Insert<T>(T entity)
            where T : Entity
        {
            session.Persist(entity);
        }

        public void Update<T>(T entity)
            where T : Entity
        {
            session.Update(entity);
        }

        public void Merge<T>(T entity)
            where T : Entity
        {
            session.Merge(entity);
        }

        public void Delete<T>(T entity)
            where T : Entity
        {
            session.Delete(entity);
        }

        public void Detach<T>(T entity)
            where T : Entity
        {
            session.Evict(entity);
        }

        public void Dispose()
        {
            session.Dispose();
        }

        public void Flush()
        {
            session.Flush();
        }
    }
}
